import 'package:easy_chat_app/commons/db/DBUtils.dart';
import 'package:easy_chat_app/commons/db/repository/LocalConversationRepository.dart';
import 'package:easy_chat_app/commons/db/repository/LocalMessageRepository.dart';
import 'package:logger/logger.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

class LocalMessageService {
  static Logger logger = Logger();

  static Future<void> addLocalMessage(LocalMessage message) async {
    try {
      await DBUtils.getDB().transaction((transaction) async {
        LocalMessageRepository.addLocalMessage(transaction, message);
      });
    } on DatabaseException catch (ex) {
      logger.e(ex);
    }
  }

  static Future<void> completeMessageSending(int? id, int? sendTime) async {
    await DBUtils.getDB().transaction((transaction) async {
      LocalMessageRepository.completeMessageSending(transaction, id, sendTime);
    });
  }

  static Future<void> changeReadState2Read(int? id) async {
    await DBUtils.getDB().transaction((transaction) async {
      LocalMessageRepository.changeReadState2Read(transaction, id);
    });
  }

  static Future<void> changeAllMsgReadState2Read(int conversationId) async {
    await DBUtils.getDB().transaction((transaction) async {
      LocalMessageRepository.changeAllMsgReadState2Read(
          transaction, conversationId);
      LocalConversationRepository.setUnReadMsgCount(
          transaction, {conversationId: 0});
    });
  }

  static Future<Map<int, int>> getUnreadMsgCount(
      List<int> conversionIdList) async {
    return DBUtils.getDB().transaction((transaction) async {
      return await LocalMessageRepository.getUnreadMsgCount(
          transaction, conversionIdList);
    });
  }

  static Future<List<LocalMessage>> queryNewLocalMsg(
      int msgCount, int conversationId) async {
    return DBUtils.getDB().transaction((transaction) async {
      return await LocalMessageRepository.queryNewLocalMsg(
          transaction, msgCount, conversationId);
    });
  }
}
